package service

import (
	"firstdemo_go/global"
	"firstdemo_go/model"
	"firstdemo_go/model/request"
	"gopkg.in/mgo.v2/bson"
)

func AddData(data model.Data) error {
	err := global.GVA_MONGODB.C("data").Insert(data)
	return err
}

func DelData(data request.DelRequest) error {
	for _, v := range data.Keys {
		err := global.GVA_MONGODB.C("data").Remove(bson.M{"key": v})
		if err != nil {
			return err
		}
	}
	return nil
}

func ModData(data model.Data) error {
	err := global.GVA_MONGODB.C("data").Update(bson.M{"key": data.Key}, data)
	return err
}

func QueryData(data request.QueryRequest) (res interface{}, err error) {
	datas := make([]model.Data, 0)
	for _, v := range data.Keys {
		var value model.Data
		err = global.GVA_MONGODB.C("data").Find(bson.M{"key": v}).One(&value)
		if err != nil {
			return nil, err
		}
		datas = append(datas, value)
	}
	res = datas
	return
}

func QueryDataOne(key string) (data model.Data, err error) {
	err = global.GVA_MONGODB.C("data").Find(bson.M{"key": key}).One(&data)
	return
}
